package com.intelligent.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 消息通知WebSocket服务端点
 */
@ServerEndpoint("/ws/notice/{userId}")
@Component
public class NoticeWebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(NoticeWebSocketServer.class);

    /**
     * 静态变量，用来记录当前在线连接数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象
     */
    private static final ConcurrentHashMap<String, NoticeWebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        logger.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            logger.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        logger.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("用户消息:" + userId + ",报文:" + message);
        // 可以群发消息
        // 消息保存到数据库、redis
        if (message != null && !message.isEmpty()) {
            try {
                // 解析发送的报文
                ObjectMapper mapper = new ObjectMapper();
                // 这里可以处理客户端发送的消息
                logger.info("收到用户 {} 的消息: {}", userId, message);
            } catch (Exception e) {
                logger.error("解析消息异常", e);
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        logger.info("发送消息到:" + userId + "，报文:" + message);
        if (userId != null && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            logger.error("用户" + userId + ",不在线！");
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendToAll(String message) throws IOException {
        for (String key : webSocketMap.keySet()) {
            try {
                webSocketMap.get(key).sendMessage(message);
            } catch (IOException e) {
                logger.error("群发消息异常", e);
            }
        }
    }

    /**
     * 发送通知消息
     */
    public static void sendNotice(String userId, Object notice) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String message = mapper.writeValueAsString(notice);
            sendInfo(message, userId);
        } catch (Exception e) {
            logger.error("发送通知消息异常", e);
        }
    }

    /**
     * 获取当前在线人数
     */
    public static synchronized int getOnlineCount() {
        return onlineCount.get();
    }

    /**
     * 在线人数加1
     */
    public static synchronized void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    /**
     * 在线人数减1
     */
    public static synchronized void subOnlineCount() {
        onlineCount.decrementAndGet();
    }

    /**
     * 获取在线用户列表
     */
    public static ConcurrentHashMap<String, NoticeWebSocketServer> getWebSocketMap() {
        return webSocketMap;
    }
}